package org.rk.core.tools.office.util.excelUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.rk.core.common.util.RkStrUtil;
import org.rk.core.tools.office.mapping.ToolOfficeExcelMapping;

/**
 * @类描述：excel导出实体映射管理类
 * @author 曹仁道
 * 2016年10月28日 下午1:54:18
 */
public class BeanMappingUtil {

	/**
	 * @方法描述：根据映射需要初始化实体bean
	 * @author:曹仁道
	 * 2016年10月28日 下午1:50:16
	 * @param mappingList 映射
	 * @param objList
	 * @param userName
	 * @return
	 */
	public static List<Map<String,Object>> initBean(List<ToolOfficeExcelMapping> mappingList,List<Map<String,Object>> objMapList,String userName){
		List<String> objMapKeyList=new ArrayList<String>();
		for (ToolOfficeExcelMapping mapping : mappingList) {
			String tableName=mapping.getTableName();
			String beanName=mapping.getBeanName();
			String localField=mapping.getLocalField();
			
			
			//首先校验该字段是否正常字段
			String times="0";
			if(localField.indexOf("#")>0){//如果出现#号表示该字段被分隔多次出现
				String[] localFieldInfo=localField.split("#");
				times=localFieldInfo[1];//记录出现次数，创建实体时对应
			}
			//生成objMapKey
			String objMapKey=ExcelUtil.genObjMapKey(beanName,tableName,times);
			if(!RkStrUtil.hasText(objMapKey)){
				continue;
			}
			if(objMapKeyList.contains(objMapKey)){//如果该变量的实体已经存在，终止
				continue;
			}
			objMapKeyList.add(objMapKey);//将该元素添加到集合中，以便后续校验重复使用
			
			Object obj=null;
			Map<String, Object> objMap=new HashMap<String, Object>();
			//方案一:反射获取实体bean
			Class<?> bean;
			try {
				bean = Class.forName(beanName);
				obj=bean.newInstance();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			//方案二:通过固定方式获取实体bean——暂不采取
			/*if("CultivateTutorStu".equals(beanName)||"cultivate_tutor_stu".equals(tableName)){//师生双选结果表
				CultivateTutorStu cultivateTutorStu=new CultivateTutorStu();
				cultivateTutorStu.setId(IDGenerator.genLongId());
				cultivateTutorStu.setCreateDate(new Date());
				cultivateTutorStu.setCreator(userName);
				if(!ZStrUtil.isEmptyAfterTrimE(times)&&!times.equals("2")){
					cultivateTutorStu.setType("2");//合作导师
				}else{
					cultivateTutorStu.setType("1");//默认都是主导师
				}
				obj=cultivateTutorStu;
			}else if("CultivateScheme".equals(beanName)||"cultivate_scheme".equals(tableName)){//师生双选结果表
				CultivateScheme cultivateScheme=new CultivateScheme();
				cultivateScheme.setId(IDGenerator.genLongId());
				cultivateScheme.setCreateDate(new Date());
				cultivateScheme.setCreator(userName);
				obj=cultivateScheme;
			}else{
				continue;
			}*/
			objMap.put("beanVariable", objMapKey);
			objMap.put("beanObject", obj);
			objMap.put("times", times);
			
			objMapList.add(objMap);
		}
		
		return objMapList;
	}
	
}
